package com.crx.springbootinit.aop;

import com.crx.springbootinit.annotation.AuthCheck;
import com.crx.springbootinit.common.ErrorCode;
import com.crx.springbootinit.exception.BusinessException;
import com.crx.springbootinit.model.entity.User;
import com.crx.springbootinit.model.enums.UserRoleEnum;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.crx.springbootinit.service.IUserService;
import com.crx.springbootinit.utils.JwtHelper;
import com.crx.springbootinit.utils.ThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限校验 AOP
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 执行拦截
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        //未携带token或redis中未存储该token，视为未登录
        String token = request.getHeader("token");
        if (token == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long userId = (Long) redisTemplate.opsForValue().get(token);
        if (userId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 获取登录用户
        User loginUser = userService.getLoginUser(userId);

        // 如果不存在该用户则拒绝
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 如果被禁用则拒绝
        if (loginUser.getRoleStatus().equals(0)) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR);
        }
        // 如果不是管理员则拒绝
        if (!loginUser.getRole().equals(1)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 通过权限校验，放行
        return joinPoint.proceed();


        //如果使用ThreadLocal
//        try {
//            ThreadLocalUtil.set("user",loginUser);
//            return joinPoint.proceed();
//        } finally {
//            ThreadLocalUtil.remove();
//        }
    }
}

